package com.example.jnidemo;

import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.res.AssetFileDescriptor;
import android.graphics.Color;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.NfcV;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.example.jnidemo.util.NfcVUtil;
import com.example.jnidemo.util.SharedPreferencesUtils;
import com.example.jnidemo.util.Tools;

import java.io.IOException;

public class MainActivity extends AppCompatActivity implements MediaPlayer.OnPreparedListener {

    private final String TAG = MainActivity.class.getSimpleName();
    private NfcAdapter mNfcAdapter;
    private PendingIntent pi;
    private TextView mTvTip;
    private TextView mTvUid;
    private TextView mTvSupplyCode;
    private TextView mTvPartNumber;
    private TextView mTvSerialNumber;
    private MediaPlayer playerSuccess = null;
    private MediaPlayer playerError = null;

    static {
        System.loadLibrary("jnidemo");
    }

    public static void start(Context context) {
        Intent starter = new Intent(context, MainActivity.class);
        context.startActivity(starter);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        String isLogin = SharedPreferencesUtils.getParam(getApplicationContext(), SPConfig.IS_LOGIN, "").toString();
        if (TextUtils.isEmpty(isLogin)) {
            RegisterActivity.start(MainActivity.this);
            finish();
            return;
        }

        playSuccess();
        playError();
        initAdapter();
        mTvTip = findViewById(R.id.tv_tip);
        mTvUid = findViewById(R.id.tv_uid);
        mTvSupplyCode = findViewById(R.id.tv_supply_code);
        mTvPartNumber = findViewById(R.id.tv_part_number);
        mTvSerialNumber = findViewById(R.id.tv_serival_number);
        Button btnClear = findViewById(R.id.btn_clear);

        String imei = Tools.getIMEI();
//        if (!TextUtils.equals("358393736303247", imei)) {
//            Toast.makeText(getApplicationContext(), getResources().getString(R.string.tip_enable_install), Toast.LENGTH_LONG).show();
//            finish();
//            return;
//        }

        btnClear.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Log.d("zddd", "onClick");

//                Log.d("zddd", "buff-" + buff);
//                byte[] bufff = buff.getBytes(StandardCharsets.UTF_8);
//                byte[] encode = AESCBCencryptbuffer("0123456789123456", bufff, bufff.length);
//                Log.d("zddd", "encode-" + ByteArrayToHexString(encode));
                String buff = "A44C6E04A908FFB322B3E3DE23132DF4";
                String uid = "A4D00A0E002302E0";

                byte[] decode = AESCBCdecryptbuffer(uid, buff.getBytes(), buff.length());
                String result = new String(decode);
                mTvUid.setText(result);

                playerError.start();
            }
        });
    }

    private void playSuccess() {
        if (playerSuccess != null) {
            playerSuccess.stop();
        }
        playerSuccess = new MediaPlayer();
        AssetFileDescriptor descriptor = null;
        try {
            descriptor = getAssets().openFd("success.mp3");
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            if (playerSuccess != null && playerSuccess.isPlaying()) {
                playerSuccess.stop();
            }
            playerSuccess.setDataSource(descriptor.getFileDescriptor(),
                    descriptor.getStartOffset(), descriptor.getLength());
            descriptor.close();
            playerSuccess.setAudioStreamType(AudioManager.STREAM_MUSIC);
            playerSuccess.setOnPreparedListener(this);
            playerSuccess.prepareAsync();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void playError() {
        if (playerError != null) {
            playerError.stop();
        }
        playerError = new MediaPlayer();
        AssetFileDescriptor descriptor = null;
        try {
            descriptor = getAssets().openFd("error.mp3");
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            if (playerError != null && playerError.isPlaying()) {
                playerError.stop();
            }
            playerError.setDataSource(descriptor.getFileDescriptor(),
                    descriptor.getStartOffset(), descriptor.getLength());
            descriptor.close();
            playerError.setAudioStreamType(AudioManager.STREAM_MUSIC);
            playerError.setOnPreparedListener(this);
            playerError.prepareAsync();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //获取数据
    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        processIntent(intent);
    }

    /**
     * @author cloin
     * 用法
     * NfcV mNfcV = NfcV.get(tag);
     * mNfcV.connect();
     * NfcVUtil mNfcVutil = new NfcVUtil(mNfcV);
     * 取得UID
     * mNfcVutil.getUID();
     * 读取block在1位置的内容
     * mNfcVutil.readOneBlock(1);
     * 从位置7开始读2个block的内容
     * mNfcVutil.readBlocks(7, 2);
     * 取得block的个数
     * mNfcVutil.getBlockNumber();
     * 取得1个block的长度
     * mNfcVutil.getOneBlockSize();
     * 往位置1的block写内容
     * mNfcVutil.writeBlock(1, new byte[]{0, 0, 0, 0})
     */
    private void processIntent(Intent intent) {
        NfcV nfcV = null;
        try {
            Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
            nfcV = NfcV.get(tag);
            nfcV.connect();
            NfcVUtil mNfcVutil = new NfcVUtil(nfcV);
            String uid = ByteArrayToHexString(tag.getId());
            Log.d(TAG, "UID:" + uid);

            clearText();

            // UID
            String firstBlock = mNfcVutil.readBlocks(0, 4);
            String decodeUID = decodeStart(uid, firstBlock);
            if (!TextUtils.equals(uid, decodeUID)) {
                mTvUid.setText(uid);
                showError();
                return;
            }
            mTvUid.setText(uid);

            String twoBlock = mNfcVutil.readBlocks(4, 4);
            decodeStart(uid, twoBlock);

            // PartNumber（零件号）
            String threeBlock = mNfcVutil.readBlocks(8, 4);
            String decodePartNumber = decodeStart(uid, threeBlock);
            String partNumber = decodePartNumber.substring(0, 11);

            // SupplierCode（供应商代码）
            String fourBlock = mNfcVutil.readBlocks(12, 4);
            String decodeSupplierCode = decodeStart(uid, fourBlock);
            String supplierCode = decodeSupplierCode.substring(1, 2) + decodeSupplierCode.substring(3, 4) + decodeSupplierCode.substring(5, 6) + decodeSupplierCode.substring(7, 8);
            if (!TextUtils.equals("1345", supplierCode)) {
                showError();
                return;
            }

            // SerialNumber（序列号）
            String fiveBlock = mNfcVutil.readBlocks(16, 4);
            String decodeSerialNumber = decodeStart(uid, fiveBlock);
            String serialNumber = decodeSerialNumber.substring(0, 14);

            showSuccess();
            mTvSupplyCode.setText(supplierCode);
            mTvSerialNumber.setText(serialNumber);
            mTvPartNumber.setText(partNumber);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (nfcV != null) {
                    nfcV.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private void clearText() {
        mTvUid.setText("");
        mTvSupplyCode.setText("");
        mTvPartNumber.setText("");
        mTvSerialNumber.setText("");
    }

    private void showError() {
        if (playerError != null) {
            playerError.start();
        }
        mTvTip.setText(getResources().getString(R.string.tip_warning));
        mTvTip.setTextColor(Color.RED);

        mTvSupplyCode.setText("****");
        mTvSerialNumber.setText("**************");
        mTvPartNumber.setText("***********");
    }

    private void showSuccess() {
        if (playerSuccess != null) {
            playerSuccess.start();
        }
        mTvTip.setText(getResources().getString(R.string.tip_success));
        mTvTip.setTextColor(getResources().getColor(R.color.color_46a220));
    }

    private String decodeStart(String uid, String buffer) {
        if (TextUtils.isEmpty(buffer)) {
            return "";
        }
        byte[] decode = AESCBCdecryptbuffer(uid, buffer.getBytes(), buffer.length());
        String decodeResult = new String(decode);
        Log.d(TAG, "解密结果:" + decodeResult);
        return decodeResult;
    }

    //启动
    @Override
    protected void onResume() {
        super.onResume();
        if (mNfcAdapter != null) {
            if (!mNfcAdapter.isEnabled()) {
                return;
            }
            mNfcAdapter.enableForegroundDispatch(this, pi, null, null);
        }
    }

    //转为16进制字符串
    private String ByteArrayToHexString(byte[] inarray) {
        int i, j, in;
        String[] hex = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A",
                "B", "C", "D", "E", "F"};
        String out = "";

        for (j = 0; j < inarray.length; ++j) {
            in = (int) inarray[j] & 0xff;
            i = (in >> 4) & 0x0f;
            out += hex[i];
            i = in & 0x0f;
            out += hex[i];
        }
        return out;
    }

    private void initAdapter() {

        //获取默认的NFC控制器
        //初始化NfcAdapter
        mNfcAdapter = NfcAdapter.getDefaultAdapter(this);
        if (mNfcAdapter == null) {
            Toast.makeText(MainActivity.this, getResources().getString(R.string.tip_not_support_nfc), Toast.LENGTH_LONG).show();
            finish();
            return;
        }
        if (!mNfcAdapter.isEnabled()) {
            Toast.makeText(MainActivity.this, getResources().getString(R.string.tip_enable_nfc), Toast.LENGTH_LONG).show();
            startActivity(new Intent("android.settings.NFC_SETTINGS"));
            finish();
            return;
        }
        //初始化PendingIntent
        // 初始化PendingIntent，当有NFC设备连接上的时候，就交给当前Activity处理
        pi = PendingIntent.getActivity(this, 0, new Intent(this, getClass())
                .addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
    }

    public native static byte[] AESCBCencryptbuffer(String uid, byte[] buff, int buffLen);

    public native static byte[] AESCBCdecryptbuffer(String uid, byte[] buff, int buffLen);

    @Override
    public void onPrepared(MediaPlayer mp) {

    }
}